/**
 * @name Account
 * @author darcrand
 * @desc 用户中心
 */

import React, { Component } from 'react'
import { inject, observer } from 'mobx-react'
import { toJS } from 'mobx'
import { Button, Form, Input, Radio, message, Breadcrumb, Modal } from 'antd'
import { AvatarUploader, TopBar, FormWrapper } from '@/components'
import { apiSingleFileUpload, apiGetGenders } from '@/apis/common'
import { apiSetPassword } from '@/apis/user'

import styles from './styles.module.less'

@inject('user')
@observer
class Account extends Component {
  state = { visiblePasswordModal: false, genderOptions: [] }
  refForm = React.createRef()
  refFormForPassword = React.createRef()

  componentDidMount() {
    this.initInfo()
  }

  initInfo = async () => {
    const { info } = this.props.user
    const userInfo = toJS(info)
    const genderOptions = await apiGetGenders()
    this.setState({ genderOptions })
    this.refForm.current.setFieldsValue({ ...userInfo, newAvatar: userInfo.avatar })
  }

  onFormFinish = async (values = {}) => {
    try {
      const { newAvatar, nickname, gender, cv, desc } = values
      const { info } = this.props.user
      const userInfo = toJS(info)

      let avatar = userInfo.avatar
      if (typeof newAvatar === 'object') {
        // 使用了新的图片
        avatar = await apiSingleFileUpload(newAvatar)
      }
      await this.props.user.update({ nickname, avatar, gender, cv, desc })
      this.initInfo()
    } catch (err) {
      console.error('更新失败')
    }
  }

  triggerUpdatePassword = () => {
    if (this.refFormForPassword.current && typeof this.refFormForPassword.current.submit === 'function') {
      this.refFormForPassword.current.submit()
    }
  }

  cancelUpdatePassword = () => {
    if (this.refFormForPassword.current) {
      this.refFormForPassword.current.resetFields()
      this.setState({ visiblePasswordModal: false })
    }
  }

  setPassword = async (values = {}) => {
    try {
      await apiSetPassword({ ...values, username: this.props.user.info.username })
      message.info('password updated')
      this.refFormForPassword.current.resetFields()
      this.setState({ visiblePasswordModal: false })
    } catch (err) {}
  }

  render() {
    const { info } = this.props.user
    const { visiblePasswordModal, genderOptions } = this.state

    return (
      <>
        <TopBar />

        <div className={styles.container}>
          <Breadcrumb className={styles.top_links}>
            <Breadcrumb.Item href='/'>Home</Breadcrumb.Item>
            <Breadcrumb.Item>Account Center</Breadcrumb.Item>
          </Breadcrumb>

          <FormWrapper>
            <Form ref={this.refForm} name='base' {...FormWrapper.FORM_ITEM_LAYOUT} onFinish={this.onFormFinish}>
              <Form.Item label='Username'>
                <div className={styles.form_disabled}>{info.username}</div>
              </Form.Item>
              <Form.Item label='Password'>
                <Button type='primary' ghost onClick={() => this.setState({ visiblePasswordModal: true })}>
                  Click to set password.
                </Button>
              </Form.Item>
              <Form.Item label='Nickname' name='nickname'>
                <Input />
              </Form.Item>
              <Form.Item label='Gender' name='gender'>
                <Radio.Group options={genderOptions} />
              </Form.Item>
              <Form.Item label='description' name='desc'>
                <Input />
              </Form.Item>
              <Form.Item label='Curriculum Vitae' name='cv'>
                <Input.TextArea rows={5} />
              </Form.Item>

              <Form.Item label='Avatar' name='newAvatar'>
                <AvatarUploader />
              </Form.Item>

              <Form.Item {...FormWrapper.TAIL_FORM_LAYOUT}>
                <Button type='primary' htmlType='submit'>
                  Update Info
                </Button>
              </Form.Item>
            </Form>
          </FormWrapper>
        </div>

        <Modal
          visible={visiblePasswordModal}
          title='Update Password'
          onOk={this.triggerUpdatePassword}
          onCancel={this.cancelUpdatePassword}
        >
          <Form ref={this.refFormForPassword} layout='vertical' name='set-password' onFinish={this.setPassword}>
            <Form.Item
              name='password'
              label='Old Password'
              rules={[
                {
                  required: true,
                  message: 'Please input your password!',
                },
              ]}
              hasFeedback
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name='newPassword'
              label='New Password'
              rules={[
                {
                  required: true,
                  message: 'Please input an new password!',
                },
              ]}
              hasFeedback
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name='confirm'
              label='Confirm Password'
              dependencies={['newPassword']}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: 'Please confirm your password!',
                },
                ({ getFieldValue }) => ({
                  validator(rule, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve()
                    }
                    return Promise.reject('The two passwords that you entered do not match!')
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>
          </Form>
        </Modal>
      </>
    )
  }
}

export default Account
